/**
 * 
 */
package face.unisannio.content;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

/**
 * @author Fabio Melillo
 *
 */
public class StudentsContentProvider extends ContentProvider {
	
	private StudentDB db;
	public static final Uri CONTENT_URI = StudentDB.CONTENT_URI;
	
	/* (non-Javadoc)
	 * @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[])
	 */
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
//		if (uri.equals(CONTENT_URI)){
//			int toReturn=db.deleteStudent(selection, selectionArgs);
//			return toReturn;
//		}
		return 0;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#getType(android.net.Uri)
	 */
	@Override
	public String getType(Uri uri) {
		return null;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
	 */
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		if (uri.equals(CONTENT_URI)){
			String nome=values.getAsString(StudentDB.STUDENT_NOME);
			String cognome=values.getAsString(StudentDB.STUDENT_COGNOME);
			String classe=values.getAsString(StudentDB.STUDENT_CLASSE);
			
			String label=nome+" "+cognome+" ["+classe+"] ";
			String uid=nome+cognome+classe;
			
			
			Student student=new Student(nome, cognome, classe, label, uid);
			Uri toReturn=db.insertStudent(student);
			return toReturn;
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#onCreate()
	 */
	@Override
	public boolean onCreate() {
		db=(new StudentDB(getContext()));
		return db.open();
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
	 */
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		
		SQLiteQueryBuilder qb=new SQLiteQueryBuilder();
		qb.setTables(db.getTableName());
		
		Cursor c=qb.query(db.getSQLiteDatabase(), projection, selection, selectionArgs, null, null, sortOrder);
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	/* (non-Javadoc)
	 * @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])
	 */
	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int toReturn = db.updateStudent(uri, values, selection, selectionArgs);
		return toReturn;
	}

}
